package com.shw.loco.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android_serialport_api.SerialPortFinder;

import com.shw.loco.R;
import com.shw.loco.adapter.LocoCalRFIDThread;
import com.shw.loco.adapter.LocoDBThread;
import com.shw.loco.adapter.LocoInfoQueue;
import com.shw.loco.adapter.LocoMainService;
import com.shw.loco.adapter.LocoNetManager;
import com.shw.loco.adapter.SerialControl;
import com.shw.loco.adapter.SerialHelper;
import com.shw.loco.database.DatabaseHelper;
import com.shw.loco.util.InfoUtils;
import com.shw.loco.util.MyFunc;
import com.shw.loco.vo.AssistBean;
import com.shw.loco.vo.ComBean;
import com.shw.loco.vo.ComPortInfo;
import com.shw.loco.vo.GPSBDInfo;

/**
 * 
 * @author HAHA
 * 
 */
public class LocoMainActivity extends Activity {
	private static final String TAG = "LocoMainActivity";
	EditText editTextRecDisp, editTextLines, editTextCOMA, dateTxt, parTxt,
			editTextTimeCOMA;
	CheckBox checkBoxAutoClear, checkBoxAutoCOMA;
	Button ButtonClear, ButtonSendCOMA, dater, datew, parr, parw, rfidButton,
			gpsbdButton, locoButton, rfidTimeButton, gpsbdTimeButton, ipbtn,
			portbtn, dbrevbtn, dbaddbtn, rfidbaudrate, gpsbdbaudrate,
			locobaudrate, exitbtn, centerbtn, configbtn, heartbtn,tablebtn,precisionbtn,butlocoadd;
	ToggleButton toggleButtonCOMA, connectBtn;
	Spinner SpinnerCOMA;
	Spinner SpinnerBaudRateCOMA;
	RadioButton radioButtonRFID, radioButtonGPSBD, radioButtonLoco, radiorfid,
			radiorfinfo, radio3G,radioadd,radiosubtract,radiodebug,radiorelease;
	SerialControl ComA;// 4个串口
	DispQueueThread DispQueue;// 刷新显示线程
	SerialPortFinder mSerialPortFinder;// 串口设备搜索
	AssistBean AssistData;// 用于界面数据序列化和反序列化
	int iRecLines = 0, RSMODE = 0, dbtable = 0;// 接收区行数
	SharedPreferences sharedPreferences;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		manager.killBackgroundProcesses(".SHW_APP");
		Intent service = new Intent(this, LocoMainService.class);
		this.stopService(service);
		ComA = new SerialControl(); 
		ComA.setContext(this);
		DispQueue = new DispQueueThread();
		DispQueue.start();
		AssistData = getAssistData();
		setControls();
		readConfig();
		LocoCalRFIDThread locoCalRFIDThread = new LocoCalRFIDThread(
				LocoMainActivity.this,sharedPreferences);
		locoCalRFIDThread.start();
	}

	private void readConfig() {
		try {
			sharedPreferences = getSharedPreferences("loco",
					Activity.MODE_PRIVATE);
			editTextRecDisp.append("3G-IP： "
					+ sharedPreferences.getString(InfoUtils.IP_INFO, null)
					+ "\n");
			editTextRecDisp.append("3G-端口： "
					+ sharedPreferences.getString(InfoUtils.IP_PORT, null)
					+ "\n");
			editTextRecDisp.append("RFID端口： "
					+ sharedPreferences.getString(InfoUtils.RFID_PORT, null)
					+ "\n");
			editTextRecDisp.append("RFID波特率： "
					+ sharedPreferences
							.getString(InfoUtils.RFID_BAUDRATE, null) + "\n");
			editTextRecDisp.append("GPS端口： "
					+ sharedPreferences.getString(InfoUtils.GPSBD_PORT, null)
					+ "\n");
			editTextRecDisp.append("GPS波特率： "
					+ sharedPreferences.getString(InfoUtils.GPSBD_BAUDRATE,
							null) + "\n");
			editTextRecDisp.append("机车端口： "
					+ sharedPreferences.getString(InfoUtils.LOCO_PORT, null)
					+ "\n");
			editTextRecDisp.append("机车波特率： "
					+ sharedPreferences
							.getString(InfoUtils.LOCO_BAUDRATE, null) + "\n");
			editTextRecDisp.append("RFID请求速率： "
					+ sharedPreferences.getString(InfoUtils.RFID_TIME, null)
					+ "\n");
			editTextRecDisp.append("GPS请求速率： "
					+ sharedPreferences.getString(InfoUtils.RFID_TIME, null)
					+ "\n");
			editTextRecDisp.append("3G发送速率： "
					+ sharedPreferences.getString(InfoUtils.CENTER_TIME, null)
					+ "\n");
			editTextRecDisp.append("3G心跳速率： "
					+ sharedPreferences.getString(InfoUtils.HEART_TIME, null)
					+ "\n");
			editTextRecDisp.append("顺时针里程： "
					+ sharedPreferences.getString(InfoUtils.OPERFLAG, null)
					+ "\n");
			editTextRecDisp.append("精度值： "
					+ sharedPreferences.getString(InfoUtils.PRECISION_IFNO, null)
					+ "\n");
		} catch (Exception e) {
		}
	}

	@Override
	public void onDestroy() {
		saveAssistData(AssistData);
		CloseComPort(ComA);
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		manager.killBackgroundProcesses("com.shw.loco");
		super.onDestroy();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		CloseComPort(ComA);
		setContentView(R.layout.main);
		setControls();
	}

	// ----------------------------------------------------
	private void setControls() {
		String appName = getString(R.string.app_name);
		try {
			PackageInfo pinfo = getPackageManager().getPackageInfo(
					"com.shw.loco", PackageManager.GET_CONFIGURATIONS);
			String versionName = pinfo.versionName;
			// String versionCode = String.valueOf(pinfo.versionCode);
			setTitle(appName + " V" + versionName);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		dateTxt = (EditText) findViewById(R.id.datetxt);
		dateTxt.setText(InfoUtils.DATE_REQ);
		dater = (Button) findViewById(R.id.dater);
		datew = (Button) findViewById(R.id.datew);
		parTxt = (EditText) findViewById(R.id.partxt);
		parTxt.setText(InfoUtils.PAR_REQ);
		parr = (Button) findViewById(R.id.parr);
		parw = (Button) findViewById(R.id.parw);
		rfidButton = (Button) findViewById(R.id.rfidbtn);
		gpsbdButton = (Button) findViewById(R.id.gpbdbtn);
		locoButton = (Button) findViewById(R.id.locobtn);
		rfidTimeButton = (Button) findViewById(R.id.rfidtime);
		gpsbdTimeButton = (Button) findViewById(R.id.gpsbdtimebtn);
		ipbtn = (Button) findViewById(R.id.ipbtn);
		portbtn = (Button) findViewById(R.id.portbtn);
		connectBtn = (ToggleButton) findViewById(R.id.connectbtn);
		dbrevbtn = (Button) findViewById(R.id.dbrevbtn);
		dbaddbtn = (Button) findViewById(R.id.dbaddbtn);
		rfidbaudrate = (Button) findViewById(R.id.RFIDbaudrate);
		gpsbdbaudrate = (Button) findViewById(R.id.GPSBDbaudrate);
		locobaudrate = (Button) findViewById(R.id.LOCObaudrate);
		exitbtn = (Button) findViewById(R.id.exitbtn);
		centerbtn = (Button) findViewById(R.id.centerbtn);
		configbtn = (Button) findViewById(R.id.configbtn);
		heartbtn = (Button) findViewById(R.id.heartbtn);
		tablebtn= (Button) findViewById(R.id.tablebtn);
		precisionbtn = (Button) findViewById(R.id.precisionbtn);
		butlocoadd=(Button) findViewById(R.id.butlocoadd);
		editTextRecDisp = (EditText) findViewById(R.id.editTextRecDisp);
		editTextLines = (EditText) findViewById(R.id.editTextLines);
		editTextCOMA = (EditText) findViewById(R.id.editTextCOMA);
		editTextCOMA.setText(InfoUtils.RFID_REQ);
		editTextTimeCOMA = (EditText) findViewById(R.id.editTextTimeCOMA);
		
		// checkBoxAutoClear = (CheckBox) findViewById(R.id.checkBoxAutoClear);
		checkBoxAutoCOMA = (CheckBox) findViewById(R.id.checkBoxAutoCOMA);
		ButtonClear = (Button) findViewById(R.id.ButtonClear);
		ButtonSendCOMA = (Button) findViewById(R.id.ButtonSendCOMA);
		toggleButtonCOMA = (ToggleButton) findViewById(R.id.toggleButtonCOMA);
		SpinnerCOMA = (Spinner) findViewById(R.id.SpinnerCOMA);
		SpinnerBaudRateCOMA = (Spinner) findViewById(R.id.SpinnerBaudRateCOMA);
		radioButtonRFID = (RadioButton) findViewById(R.id.radioButtonrfid);
		radioButtonGPSBD = (RadioButton) findViewById(R.id.radioButtonrgpbs);
		radioButtonLoco = (RadioButton) findViewById(R.id.radioButtonloco);
		radiorfid = (RadioButton) findViewById(R.id.radiorfid);
		radiorfinfo = (RadioButton) findViewById(R.id.radiorfinfo);
		radio3G = (RadioButton) findViewById(R.id.radioButton3G);
		radioadd= (RadioButton) findViewById(R.id.radioadd);
		radiosubtract= (RadioButton) findViewById(R.id.radiosubtract);
//		radiodebug= (RadioButton) findViewById(R.id.radiodebug);
//		radiorelease=(RadioButton) findViewById(R.id.radiorelease);
		editTextCOMA.setOnEditorActionListener(new EditorActionEvent());
		editTextTimeCOMA.setOnEditorActionListener(new EditorActionEvent());
		editTextCOMA.setOnFocusChangeListener(new FocusChangeEvent());
		editTextTimeCOMA.setOnFocusChangeListener(new FocusChangeEvent());

		radioButtonRFID.setOnClickListener(new radioButtonClickEvent());
		radioButtonGPSBD.setOnClickListener(new radioButtonClickEvent());
		radioButtonLoco.setOnClickListener(new radioButtonClickEvent());
		radiorfid.setOnClickListener(new radioButtonClickEvent());
		radiorfinfo.setOnClickListener(new radioButtonClickEvent());
		radio3G.setOnClickListener(new radioButtonClickEvent());
		radioadd.setOnClickListener(new radioButtonClickEvent());
		radiosubtract.setOnClickListener(new radioButtonClickEvent());
//		radiodebug.setOnClickListener(new radioButtonClickEvent());
//		radiorelease.setOnClickListener(new radioButtonClickEvent());
		ButtonClear.setOnClickListener(new ButtonClickEvent());
		ButtonSendCOMA.setOnClickListener(new ButtonClickEvent());
		dater.setOnClickListener(new ButtonClickEvent());
		datew.setOnClickListener(new ButtonClickEvent());
		parr.setOnClickListener(new ButtonClickEvent());
		parw.setOnClickListener(new ButtonClickEvent());
		rfidButton.setOnClickListener(new ButtonClickEvent());
		gpsbdButton.setOnClickListener(new ButtonClickEvent());
		locoButton.setOnClickListener(new ButtonClickEvent());
		rfidTimeButton.setOnClickListener(new ButtonClickEvent());
		gpsbdTimeButton.setOnClickListener(new ButtonClickEvent());
		ipbtn.setOnClickListener(new ButtonClickEvent());
		portbtn.setOnClickListener(new ButtonClickEvent());
		connectBtn
				.setOnCheckedChangeListener(new ToggleButtonCheckedChangeEvent());
		dbrevbtn.setOnClickListener(new ButtonClickEvent());
		dbaddbtn.setOnClickListener(new ButtonClickEvent());
		rfidbaudrate.setOnClickListener(new ButtonClickEvent());
		gpsbdbaudrate.setOnClickListener(new ButtonClickEvent());
		locobaudrate.setOnClickListener(new ButtonClickEvent());
		exitbtn.setOnClickListener(new ButtonClickEvent());
		centerbtn.setOnClickListener(new ButtonClickEvent());
		configbtn.setOnClickListener(new ButtonClickEvent());
		heartbtn.setOnClickListener(new ButtonClickEvent());
		tablebtn.setOnClickListener(new ButtonClickEvent());
		precisionbtn.setOnClickListener(new ButtonClickEvent());
		butlocoadd.setOnClickListener(new ButtonClickEvent());
		toggleButtonCOMA
				.setOnCheckedChangeListener(new ToggleButtonCheckedChangeEvent());
		checkBoxAutoCOMA.setOnCheckedChangeListener(new CheckBoxChangeEvent());

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.baudrates_value,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		SpinnerBaudRateCOMA.setAdapter(adapter);
		SpinnerBaudRateCOMA.setSelection(12);

		mSerialPortFinder = new SerialPortFinder();
		String[] entryValues = mSerialPortFinder.getAllDevicesPath();
		List<String> allDevices = new ArrayList<String>();
		for (int i = 0; i < entryValues.length; i++) {
			allDevices.add(entryValues[i]);
		}
		ArrayAdapter<String> aspnDevices = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allDevices);
		aspnDevices
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		SpinnerCOMA.setAdapter(aspnDevices);
		if (allDevices.size() > 0) {
			SpinnerCOMA.setSelection(0);
		}
		SpinnerCOMA.setOnItemSelectedListener(new ItemSelectedEvent());
		SpinnerBaudRateCOMA.setOnItemSelectedListener(new ItemSelectedEvent());
		DispAssistData(AssistData);
	}

	// ----------------------------------------------------串口号或波特率变化时，关闭打开的串口
	class ItemSelectedEvent implements Spinner.OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if ((arg0 == SpinnerCOMA) || (arg0 == SpinnerBaudRateCOMA)) {
				CloseComPort(ComA);
				checkBoxAutoCOMA.setChecked(false);
				toggleButtonCOMA.setChecked(false);
			}
		}

		public void onNothingSelected(AdapterView<?> arg0) {
		}

	}

	// ----------------------------------------------------编辑框焦点转移事件
	class FocusChangeEvent implements EditText.OnFocusChangeListener {
		public void onFocusChange(View v, boolean hasFocus) {
			if (v == editTextCOMA) {
				setSendData(editTextCOMA);
			} else if (v == editTextTimeCOMA) {
				setDelayTime(editTextTimeCOMA);
			}
		}
	}

	// ----------------------------------------------------编辑框完成事件
	class EditorActionEvent implements EditText.OnEditorActionListener {
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (v == editTextCOMA) {
				setSendData(editTextCOMA);
			} else if (v == editTextTimeCOMA) {
				setDelayTime(editTextTimeCOMA);
			}
			return false;
		}
	}

	// ----------------------------------------------------Txt、Hex模式选择
	class radioButtonClickEvent implements RadioButton.OnClickListener {
		public void onClick(View v) {
			if (v == radioButtonRFID) {
				RSMODE = 0;
				// if (!toggleButtonCOMA.isChecked())
				checkBoxAutoCOMA.setEnabled(true);
			} else if (v == radioButtonGPSBD) {
				RSMODE = 1;
				// if (!toggleButtonCOMA.isChecked())
				checkBoxAutoCOMA.setEnabled(true);
			} else if (v == radioButtonLoco) {
				RSMODE = 2;
				// if (!toggleButtonCOMA.isChecked())
				checkBoxAutoCOMA.setEnabled(true);
			} else if (v == radiorfid) {
				dbtable = 0;
			} else if (v == radiorfinfo) {
				dbtable = 2;
			} else if (v == radio3G) {
				RSMODE = 3;
				checkBoxAutoCOMA.setEnabled(false);
			}else if (v == radioadd) {
				setParemeter(InfoUtils.OPERFLAG, "add");
			}else if (v == radiosubtract) {
				setParemeter(InfoUtils.OPERFLAG, "subtract");
			}
			/*else if (v == radiodebug) {
				setParemeter(InfoUtils.ISDEBUG, "debug");
			}else if (v == radiorelease) {
				setParemeter(InfoUtils.ISDEBUG, "release");
			}*/
		}
	}

	boolean g3LoopFlag = false;
	Runnable handlerAutoNet = new Runnable() {

		@Override
		public void run() {
			while (g3LoopFlag) {
				try {
					LocoInfoQueue.resultToCenterVector.add(InfoUtils
							.HexToByteArr(editTextCOMA.getText().toString()));
				} catch (Exception e) {
					ShowMessage(e.getMessage() + "  数据有误请检查");
				}
				updateBarHandler.postDelayed(handlerAutoNet, 3000);
				try {
					Thread.sleep(Integer.valueOf(editTextTimeCOMA.getText()
							.toString()));
				} catch (NumberFormatException e) {
					ShowMessage(e.getMessage() + "  数据有误请检查");
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};
	Handler updateBarHandler = new Handler();

	// ----------------------------------------------------自动发送
	class CheckBoxChangeEvent implements CheckBox.OnCheckedChangeListener {

		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (buttonView == checkBoxAutoCOMA) {
				if (!toggleButtonCOMA.isChecked() && isChecked) {
					buttonView.setChecked(false);
					// LocoMainActivity.this.g3LoopFlag=false;
					// updateBarHandler.removeCallbacks(handlerAutoNet);
					return;
				}
				if (RSMODE < 3) {
					SetLoopData(ComA, editTextCOMA.getText().toString());
					SetAutoSend(ComA, isChecked);
				} else {
					LocoMainActivity.this.g3LoopFlag = true;
					updateBarHandler.post(handlerAutoNet);

				}
			}
		}
	}

	/**
	 * 设置参数
	 * 
	 * @param keys
	 * @param values
	 */
	public void setParemeter(String keys, String values) {
		SharedPreferences sharedPreferences = getSharedPreferences("loco",
				Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putString(keys, values);
		ShowMessage("设置成功");
		editor.commit();
	}

	// ----------------------------------------------------清除按钮、发送按钮
	class ButtonClickEvent implements View.OnClickListener {
		public void onClick(View v) {
			if (v == ButtonClear) {
				editTextRecDisp.setText("");
			} else if (v == ButtonSendCOMA) {
				switch (RSMODE) {
				case 0:
				case 1:
				case 2:
					sendPortData(ComA, editTextCOMA.getText().toString());
					break;
				case 3:
					try {
						LocoInfoQueue.resultToCenterVector
								.add(InfoUtils.HexToByteArr(editTextCOMA
										.getText().toString()));
					} catch (Exception e) {
						ShowMessage(e.getMessage() + "  数据有误请检查");
					}
					break;
				default:
					break;
				}

			} else if (v == dater) {
				sendPortData(ComA, InfoUtils.DATE_REQ);
			} else if (v == datew) {
				// sendPortData(ComA, dateTxt.getText().toString());
				try {
					sendPortData(ComA, InfoUtils.dateToHexStr());
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (v == parr) {
				sendPortData(ComA, InfoUtils.PAR_REQ);
			} else if (v == parw) {
//				sendPortData(ComA, parTxt.getText().toString());
				LayoutInflater inflater = getLayoutInflater();
				final View layout = inflater.inflate(R.layout.par_write,null);	
				AlertDialog.Builder builder=new AlertDialog.Builder(LocoMainActivity.this);
//				builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
				builder.setTitle("参数下发");
				builder.setView(layout);
				builder.setPositiveButton("确定", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try{
							EditText editText3 =(EditText) layout.findViewById(R.id.editText3);
							EditText editText2 =(EditText) layout.findViewById(R.id.editText2);
							EditText editText1 =(EditText) layout.findViewById(R.id.editText1);
						String v1=editText1.getText().toString();
						String v2=editText2.getText().toString();
						String v3=editText3.getText().toString();
						String vresult="6801040A0301"+v1+"02"+v2+"03"+InfoUtils.leftAdding(Integer.toHexString(Integer.parseInt(v3)), "0", 4);
						vresult=vresult+InfoUtils.CRC_16(InfoUtils.HexString2Bytes(vresult));
						sendPortData(ComA, vresult);
						}catch(Exception e){
							ShowMessage("下发参数有误 "+e.getMessage());
						}
					}
				} );
				builder.setNegativeButton("取消", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				builder.show();
			} else if (v == rfidButton) {
				Log.d(TAG, SpinnerCOMA.getSelectedItem().toString());
				setParemeter(InfoUtils.RFID_PORT, SpinnerCOMA.getSelectedItem()
						.toString());
			} else if (v == gpsbdButton) {
				Log.d(TAG, SpinnerCOMA.getSelectedItem().toString());
				setParemeter(InfoUtils.GPSBD_PORT, SpinnerCOMA
						.getSelectedItem().toString());
			} else if (v == locoButton) {
				Log.d(TAG, SpinnerCOMA.getSelectedItem().toString());
				setParemeter(InfoUtils.LOCO_PORT, SpinnerCOMA.getSelectedItem()
						.toString());
			} else if (v == rfidTimeButton) {
				Log.d(TAG, editTextCOMA.getText().toString());
				try {
					Integer.valueOf(editTextCOMA.getText().toString());
					setParemeter(InfoUtils.RFID_TIME, editTextCOMA.getText()
							.toString());
				} catch (Exception e) {
					ShowMessage("请求速率只允许为数字");
				}
			} else if (v == gpsbdTimeButton) {
				Log.d(TAG, editTextCOMA.getText().toString());
				try {
					Integer.valueOf(editTextCOMA.getText().toString());
					setParemeter(InfoUtils.GPSBD_TIME, editTextCOMA.getText()
							.toString());
				} catch (Exception e) {
					ShowMessage("读取速率只允许为数字");
				}

			} else if (v == ipbtn) {
				Log.d(TAG, editTextCOMA.getText().toString());
				setParemeter(InfoUtils.IP_INFO, editTextCOMA.getText()
						.toString());
			} else if (v == portbtn) {
				Log.d(TAG, editTextCOMA.getText().toString());
				try {
					Integer.valueOf(editTextCOMA.getText().toString());
					setParemeter(InfoUtils.IP_PORT, editTextCOMA.getText()
							.toString());
				} catch (Exception e) {
					ShowMessage("端口只允许为数字");
				}

			} else if (v == dbrevbtn) {
				LocoDBThread ldbt = new LocoDBThread(LocoDBThread.DB_RECOVER,
						dbtable, LocoMainActivity.this, "", true);
				ldbt.start();
			} else if (v == dbaddbtn) {
				LocoDBThread ldbt = new LocoDBThread(LocoDBThread.DB_ADD,
						dbtable, LocoMainActivity.this, "", true);
				ldbt.start();
			} else if (v == rfidbaudrate) {
				setParemeter(InfoUtils.RFID_BAUDRATE, SpinnerBaudRateCOMA
						.getSelectedItem().toString());
			} else if (v == gpsbdbaudrate) {
				setParemeter(InfoUtils.GPSBD_BAUDRATE, SpinnerBaudRateCOMA
						.getSelectedItem().toString());
			} else if (v == locobaudrate) {
				setParemeter(InfoUtils.LOCO_BAUDRATE, SpinnerBaudRateCOMA
						.getSelectedItem().toString());
			} else if (v == exitbtn) {
				LocoMainActivity.this.finish();
				ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
				manager.killBackgroundProcesses("com.shw.loco");
			} else if (v == centerbtn) {
				try {
					Integer.valueOf(editTextCOMA.getText().toString());
					setParemeter(InfoUtils.CENTER_TIME, editTextCOMA.getText()
							.toString());
				} catch (Exception e) {
					ShowMessage("发送速率只允许为数字");
				}

			} else if (v == heartbtn) {
				try {
					Integer.valueOf(editTextCOMA.getText().toString());
					setParemeter(InfoUtils.HEART_TIME, editTextCOMA.getText()
							.toString());
				} catch (Exception e) {
					ShowMessage("心跳速率只允许为数字");
				}

			} else if (v == configbtn) {
				readConfig();
			} else if (v == tablebtn) {
				 DatabaseHelper databaseHelper= new DatabaseHelper(LocoMainActivity.this);
				 try {
					databaseHelper.alterTable();
//					 databaseHelper.insertTestData();
					ShowMessage("数据表变更成功");
				} catch (Exception e) {
					ShowMessage(e.getMessage());
				}
			}else if (v == precisionbtn) {
				try {
					Integer.valueOf(editTextCOMA.getText().toString());
					setParemeter(InfoUtils.PRECISION_IFNO, editTextCOMA.getText()
							.toString());
				} catch (Exception e) {
					ShowMessage("精度值只允许为数字");
				}
			}else if (v == butlocoadd) {
				try {
					int iss=Integer.valueOf(editTextCOMA.getText().toString());
					if(iss>65535)
						throw new Exception("error");
					setParemeter(InfoUtils.LOCOTERMINAL, Integer.toHexString(Integer.valueOf(editTextCOMA.getText()
							.toString())));
				} catch (Exception e) {
					ShowMessage("终端ID最大只允许到65535");
				}
			}  
			

		}
	}

	LocoNetManager lnm = null;

	// ----------------------------------------------------打开关闭串口
	class ToggleButtonCheckedChangeEvent implements
			ToggleButton.OnCheckedChangeListener {
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {

			if (buttonView == toggleButtonCOMA) {
				if (isChecked) {
					ComA.setPort(SpinnerCOMA.getSelectedItem().toString());
					ComA.setContext(LocoMainActivity.this);
					ComA.setBaudRate(SpinnerBaudRateCOMA.getSelectedItem()
							.toString());
					SharedPreferences sharedPreferences = getSharedPreferences(
							"loco", Activity.MODE_PRIVATE);
					int rfid_time = 0;
					int gps_time = 0;
					try {
						rfid_time = Integer.valueOf(sharedPreferences
								.getString(InfoUtils.RFID_TIME, ""));
						if (rfid_time <= 50)
							throw new Exception("rfid_time exception");
					} catch (Exception e) {
						rfid_time = InfoUtils.SERVER_DELAY;
					}
					try { 
						gps_time = Integer.valueOf(sharedPreferences.getString(
								InfoUtils.GPSBD_TIME, ""));
						if (gps_time <= 50)
							throw new Exception("gps_time exception");
					} catch (Exception e) {
						gps_time = InfoUtils.GPS_DELAY;
					}
					switch (RSMODE) {
					case 0:
						ComA.setPortinfo(InfoUtils.PORT485_RFID);
						ComA.setDelay(rfid_time);
						OpenComPort(ComA);
						break;
					case 1:
						ComA.setPortinfo(InfoUtils.PORT232_GPS);
						ComA.setDelay(gps_time);
						OpenComPort(ComA);
						break;
					case 2:
						ComA.setPortinfo(InfoUtils.PORT485_LOCO);
						OpenComPort(ComA);
						break;
					case 3:
						ShowMessage("开启3G连接请使用3G设置下方的开关");
						buttonView.setChecked(false);
						break;
					default:
						break;
					}
				} else {
					CloseComPort(ComA);
					if (connectBtn.isChecked() && toggleButtonCOMA.isChecked()) {
						DispQueue.interrupt();
					}
				}
			}
			if (buttonView == connectBtn) {

				SharedPreferences sharedPreferences = getSharedPreferences(
						"loco", Activity.MODE_PRIVATE);
				if (isChecked) {
					checkBoxAutoCOMA.setEnabled(false);

					lnm = new LocoNetManager(LocoMainActivity.this,
							sharedPreferences);
					lnm.startSendRevThread();

					// RFID 测试
					String recInfo="6801833B020CBBBBBBBBBBBBBBBBBBBB10170C222233B2DDD9014000000000000000000000870200000000000000000032C81341AA0A964017282103010114278B";
					try {
						GPSBDInfo gpsbdInfo = new GPSBDInfo();
						gpsbdInfo.setGbMode("$GPRMC");
						gpsbdInfo.setGbTime("151515.115");
						gpsbdInfo.setGbState("A");
						gpsbdInfo.setGbLat("34.142373134");
						gpsbdInfo.setGbLatStatus("N");
						gpsbdInfo.setGbLon("108.539701757");
						gpsbdInfo.setGbLonStatus("E");
						gpsbdInfo.setGbSpeed("110.1");
						gpsbdInfo.setGbCourse("120");
						gpsbdInfo.setGbDate("121213");
						gpsbdInfo.setGbDeclination("180");
						gpsbdInfo.setGbDecCourse("E");
						gpsbdInfo.setGbCheck("0000");
						LocoInfoQueue.gpsbdVector.add(gpsbdInfo);
						ComPortInfo ComRecData = new ComPortInfo("/dev", recInfo,0);
						Thread.sleep(200);
						recInfo="6801833B010CBBBBBBBBBBBBBBBBBBBB10210CBBBBBBBBBBBBBBBBBBBB1014000000000000870200000000000000000032C81341AA0A964017282103020114278B";
						ComPortInfo ComRecDatas = new ComPortInfo("/dev", recInfo,0);
						Thread.sleep(200);
						recInfo="6801833B010CE20090002506020024101F3E0CBBBBBBBBBBBBBBBBBBBB1014000000000000870200000000000000000032C81341AA0A964017282103030114278B";
						ComPortInfo ComRecDatass = new ComPortInfo("/dev", recInfo,0);
						Thread.sleep(200);
						recInfo="6801833B020CE2009000250602070420EA6B0CE2009000250602011120A6010000000000E4849206000006000000230070F3654440E2534447081403120314B3E612";
						ComPortInfo ComRecDatasss = new ComPortInfo("/dev", recInfo,0);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					/*RFIDBoardInfo rfidBI = new RFIDBoardInfo();
					rfidBI.setInfoLength(1);
					rfidBI.setRfCount(1);
					rfidBI.setRfInfo("");
					rfidBI.setRf1len(12);
					rfidBI.setRf1ID("BBBBBBBBBBBBBBBBBBBB1021");
					rfidBI.setRfCourse("00");
					rfidBI.setRfCal("");
					rfidBI.setRfSpeed("100");
					rfidBI.setAllMil("900");
					rfidBI.setRfMil0x("0a0a0a0a");
					rfidBI.setRfMil("0.5");
					try {
 						rfidBI.setRfDate0x(InfoUtils.dateToHexStrNoCRC());
						rfidBI.setRfDate(InfoUtils.hexToDateStr(InfoUtils
								.dateToHexStr()));
						rfidBI.setRfCRC("0000");
//						LocoInfoQueue.addRFIDV(rfidBI);
					} catch (Exception e) {
						e.printStackTrace();
					}
					// GPS测试
					try {
						GPSBDInfo gpsbdInfo = new GPSBDInfo();
						gpsbdInfo.setGbMode("$GPRMC");
						gpsbdInfo.setGbTime("151515.115");
						gpsbdInfo.setGbState("A");
						gpsbdInfo.setGbLat("34.142311467");
						gpsbdInfo.setGbLatStatus("N");
						gpsbdInfo.setGbLon("108.539790157");
						gpsbdInfo.setGbLonStatus("E");
						gpsbdInfo.setGbSpeed("110.1");
						gpsbdInfo.setGbCourse("120");
						gpsbdInfo.setGbDate("121213");
						gpsbdInfo.setGbDeclination("180");
						gpsbdInfo.setGbDecCourse("E");
						gpsbdInfo.setGbCheck("0000");
						rfidBI.setGpsbdInfo(gpsbdInfo);
						LocoInfoQueue.addRFIDV(rfidBI);
						LocoInfoQueue.gpsbdVector.clear();
						LocoInfoQueue.gpsbdVector.add(gpsbdInfo);
					} catch (Exception e) {
						System.out.println(e.getMessage());
					}*/

				} else {
					if (connectBtn.isChecked() && toggleButtonCOMA.isChecked()) {
						DispQueue.interrupt();
					}
					lnm.stopSendRevThread();
				}
			}
		}
	}

	// ----------------------------------------------------刷新显示线程
	private class DispQueueThread extends Thread {
		private Queue<ComBean> QueueList = new LinkedList<ComBean>();

		@Override
		public void run() {
			super.run();
			while (!isInterrupted()) {
				// final ComBean ComData;
				final ComPortInfo ComData;
				while ((ComData = LocoInfoQueue.getComQueue()) != null) {
					runOnUiThread(new Runnable() {
						public void run() {
							DispRecData(ComData);
						}
					});
					try {
						Thread.sleep(100);// 显示性能高的话，可以把此数值调小。
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				}
			}
		}

		public synchronized void AddQueue(ComBean ComData) {
			QueueList.add(ComData);
		}
	}

	// ----------------------------------------------------刷新界面数据
	private void DispAssistData(AssistBean AssistData) {
		editTextCOMA.setText(AssistData.getSendA());
		setSendData(editTextCOMA);
		editTextTimeCOMA.setText(AssistData.sTimeA);
		setDelayTime(editTextTimeCOMA);
	}

	// ----------------------------------------------------保存、获取界面数据
	private void saveAssistData(AssistBean AssistData) {
		AssistData.sTimeA = editTextTimeCOMA.getText().toString();
		SharedPreferences msharedPreferences = getSharedPreferences(
				"ComAssistant", Context.MODE_PRIVATE);
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(AssistData);
			String sBase64 = new String(Base64.encode(baos.toByteArray(), 0));
			SharedPreferences.Editor editor = msharedPreferences.edit();
			editor.putString("AssistData", sBase64);
			editor.commit();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// ----------------------------------------------------
	private AssistBean getAssistData() {
		SharedPreferences msharedPreferences = getSharedPreferences(
				"ComAssistant", Context.MODE_PRIVATE);
		AssistBean AssistData = new AssistBean();
		try {
			String personBase64 = msharedPreferences
					.getString("AssistData", "");
			byte[] base64Bytes = Base64.decode(personBase64.getBytes(), 0);
			ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			AssistData = (AssistBean) ois.readObject();
			return AssistData;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AssistData;
	}

	// ----------------------------------------------------设置自动发送延时
	private void setDelayTime(TextView v) {
		if (v == editTextTimeCOMA) {
			AssistData.sTimeA = v.getText().toString();
			SetiDelayTime(ComA, v.getText().toString());
		}
	}

	// -----------------------------------------------------设置自动发送数据
	private void setSendData(TextView v) {

		if (v == editTextCOMA) {
			AssistData.setSendA(v.getText().toString());
			SetLoopData(ComA, v.getText().toString());
		}

	}

	// ----------------------------------------------------设置自动发送延时
	private void SetiDelayTime(SerialHelper ComPort, String sTime) {
		ComPort.setDelay(Integer.parseInt(sTime));
	}

	// ----------------------------------------------------设置自动发送数据
	private void SetLoopData(SerialHelper ComPort, String sLoopData) {

		try {
			ComPort.setHexLoopData(sLoopData);
		} catch (Exception e) {
			ShowMessage(e.getMessage() + "  数据有误请检查");
		}
	}

	// ----------------------------------------------------显示接收数据
	private void DispRecDatas(ComBean ComRecData) {
		StringBuilder sMsg = new StringBuilder();
		sMsg.append(ComRecData.sRecTime);
		sMsg.append("[");
		sMsg.append(ComRecData.sComPort);
		sMsg.append("]");
		sMsg.append("[Hex] ");
		sMsg.append(MyFunc.ByteArrToHex(ComRecData.bRec));
		sMsg.append("\r\n");
		editTextRecDisp.append(sMsg);
		iRecLines++;
		editTextLines.setText(String.valueOf(iRecLines));
		if (iRecLines > 500)// 达到500项自动清除
		{
			editTextRecDisp.setText("");
			editTextLines.setText("0");
			iRecLines = 0;
		}
	}

	private void DispRecData(ComPortInfo ComRecData) {
		StringBuilder sMsg = new StringBuilder();
		/*
		 * sMsg.append(ComRecData.getRecTime()); if (radioButtonTxt.isChecked())
		 * { sMsg.append("[Txt] "); sMsg.append(ComRecData.getRecInfo()); }else
		 * if (radioButtonHex.isChecked()) { sMsg.append("[Hex] ");
		 * sMsg.append(MyFunc.ByteArrToHex(ComRecData.getPortByte())); }
		 */
		if (ComRecData.getRecInfo().startsWith("68018207")) {
			String str = ComRecData.getRecInfo().substring(4 * 2);
			String dateweeks = InfoUtils.hexToDateStr(str.substring(0, 7 * 2))
					+ " " + InfoUtils.hexToWeekStr(str.substring(0, 7 * 2));
			dateTxt.setText(dateweeks);
		} else if (ComRecData.getRecInfo().startsWith("680185")) {
			parTxt.setText(ComRecData.getRecInfo());
		} else if (ComRecData.getRecInfo().toUpperCase().startsWith("68018100")) {
			ShowMessage("下发时钟正确");
		} else if (ComRecData.getRecInfo().toUpperCase().startsWith("6801C100")) {
			ShowMessage("下发时钟错误");
		} else if (ComRecData.getRecInfo().toUpperCase().startsWith("6801C200")) {
			ShowMessage("读取时钟错误");
		} else if (ComRecData.getRecInfo().toUpperCase().startsWith("68018400")) {
			ShowMessage("下写参数正确");
		} else if (ComRecData.getRecInfo().toUpperCase().startsWith("6801C400")) {
			ShowMessage("下写参数错误");
		} else if (ComRecData.getRecInfo().toUpperCase().startsWith("6801C500")) {
			ShowMessage("读取参数错误");
		} else {
			sMsg.append("[Hex] ");
			sMsg.append(ComRecData.getRecInfo());
			sMsg.append("\r\n");
			editTextRecDisp.append(sMsg);
			iRecLines++;
			editTextLines.setText(String.valueOf(iRecLines));
			if (iRecLines > 500)// 达到500项自动清除
			{
				editTextRecDisp.setText("");
				editTextLines.setText("0");
				iRecLines = 0;
			}
		}
	}

	// ----------------------------------------------------设置自动发送模式开关
	private void SetAutoSend(SerialHelper ComPort, boolean isAutoSend) {
		if (isAutoSend) {
			ComPort.startSend();
		} else {
			ComPort.stopSend();
		}
	}

	// ----------------------------------------------------串口发送
	private void sendPortData(SerialHelper ComPort, String sOut) {
		if (ComPort != null && ComPort.isOpen()) {
			try {
				ComPort.sendHex(sOut);
			} catch (Exception e) {
				ShowMessage(e.getMessage() + "  数据有误请检查");
			}
			/*
			 * if (radioButtonTxt.isChecked()) { ComPort.sendTxt(sOut); }else if
			 * (radioButtonHex.isChecked()) { ComPort.sendHex(sOut); }
			 */
		}
	}

	// ----------------------------------------------------关闭串口
	private void CloseComPort(SerialHelper ComPort) {
		if (ComPort != null) {
			ComPort.stopSend();
			ComPort.close();
		}
	}

	// ----------------------------------------------------打开串口
	private void OpenComPort(SerialHelper ComPort) {
		try {
			ComPort.open();
		} catch (SecurityException e) {
			ShowMessage("打开串口失败:没有串口读/写权限!");
		} catch (IOException e) {
			ShowMessage("打开串口失败:未知错误!");
		} catch (InvalidParameterException e) {
			ShowMessage("打开串口失败:参数错误!");
		}
	}

	// ------------------------------------------显示消息

	private void ShowMessage(String sMsg) {
		Toast.makeText(this, sMsg, Toast.LENGTH_SHORT).show();
	}

}
